#!/usr/bin/env python
# -*- coding: utf-8 -*-

# package  : j0urn4l - PyGTK Journal Manager
# version  : $Id$
# copyright: Copyright (c) 2008-2009 Bertrand Kintanar <b3rxkintanar@gmail.com>
# license  : http://opensource.org/licenses/gpl-3.0.html
# url      : http://j0urn4l.googlecode.com/
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# If you find any bugs or have any suggestions email: b3rxkintanar@gmail.com
# URL: http://j0urn4l.googlecode.com/
#
# POSvrSys needs the following to function properly:
#   python >= 2.5.1, gtk >= 2.14.1, pygtk >= 2.12.2, 
#   sqlite >= 2.3.5, sqlalchemy >= 0.5.0

__version__ = "$Rev$"
# $HeadURL$

_ = lambda x : x

from config import *
from config import __appversion__

try:
    
    import base64
    import datetime
    import gettext
    import locale
    import os
    import platform
    import re
    import sys
    
except ImportError, e:
    
    # Do not translate
    print "Import error %s cannot start:" % APP_NAME, e
    
    sys.exit(1)

try:
    
    import gobject
    import pygtk
    pygtk.require20()
    
    import gtk
    
    try:
        
        assert gtk.ver >= (2, 14, 1)
        
    except AssertionError:
        
        # Do not translate
        print "%s requires GTK+ 2.14.1 or higher, but %s was found" \
              % (APP_NAME, gtk.ver)
        
        sys.exit(1)
        
    if DEBUG:
        
        # Do not translate
        print "Checking pygtk >= 2.0.......... Found"
        print "Checking gtk+  >= 2.14.1....... Found"
        
except ImportError, e:

    # Do not translate
    print "Import error %s cannot start:" % APP_NAME, e
    
    sys.exit(1)
    
class J0urn4l(object):
    
    def __init__(self):
        
        if DEBUG:
            
            print _("Initializing UI with gtk.Builder")
            
        #Get the local path
        self.local_path = os.path.realpath(os.path.dirname(sys.argv[0]))
        #Translation stuff
        #self.initialize_translation()
        
        #Set the gtk.Builder from xml
        self.builder = gtk.Builder()
        self.builder.add_from_file(os.path.join(self.local_path, "ui", "j0urn4l.xml"))
        
        #Get the Main Window Object
        self.main_window = self.builder.get_object("mainWindow")
        
        #Initialize some widgets
        self.initialize_widgets()
        
        if LOGIN:
            
            self.security()
            self.set_permissions()
            
        self.baseTitle = APP_NAME + " " + __appversion__ + " r" + __version__.split(" ")[1]
        self.currentFilename = "Untitled.j0urn4l"
        self.main_window.set_title(self.baseTitle + " - " + self.currentFilename)
        self.main_window.maximize()
        
        #Connect with yourself
        self.builder.connect_signals(self)
        
        self.main_window.show_all()
        
    #***************************************************************************
    # Initializations
    #***************************************************************************
    def initialize_widgets(self):
    
        self.mainTextView = self.builder.get_object("mainTextView")
        self.buffer = self.mainTextView.get_buffer()
        self.subTextView  = self.builder.get_object("subTextView")
        self.appClipboard = gtk.Clipboard()
        self.openFileDialog = self.builder.get_object("openFileDialog")
        self.openDialogOpenButton = self.builder.get_object("openDialogOpenButton")
        self.saveToolButton = self.builder.get_object("saveToolButton")
        
    #***************************************************************************
    # Signal Handlers
    #***************************************************************************
    def on_mainWindow_destroy(self, widget):
        
        """
        Called when the application is going to quit
        """
        
        gtk.main_quit()
        
    def on_addEntryButton_clicked(self, widget):
        
        dt = str(datetime.datetime.today())[0:-7]
        
        textBuffer = self.subTextView.get_buffer()
        
        startIter = textBuffer.get_start_iter()
        endIter = textBuffer.get_end_iter()
        
        text = dt + " " + textBuffer.get_text(startIter, endIter) + '\n'
        
        self.insertText(text)
        self.main_window.set_title(self.baseTitle + " - *" + self.currentFilename)
        self.saveToolButton.set_sensitive(True)
        
        textBuffer.select_range(startIter, endIter)
        textBuffer.delete_selection(True, True)
        
    def on_openToolButton_clicked(self, widget):
        
        filter = gtk.FileFilter()
        filter.set_name("All files")
        filter.add_pattern("*")
        self.openFileDialog.add_filter(filter)
        self.openFileDialog.set_transient_for(self.main_window)
        
        self.openFileDialog.set_action(gtk.FILE_CHOOSER_ACTION_OPEN)
        
        image = gtk.Image()
        image.set_from_stock(gtk.STOCK_OPEN, gtk.ICON_SIZE_BUTTON)
        
        self.openDialogOpenButton.set_image(image)
        self.openDialogOpenButton.set_label("_Open")
        
        if self.openFileDialog.run() == gtk.RESPONSE_OK:
            
            startIter = self.buffer.get_start_iter()
            endIter   = self.buffer.get_end_iter()
            self.buffer.select_range(startIter, endIter)
            self.buffer.delete_selection(True, True)
            
            
            filename = self.openFileDialog.get_filename()
            for line in file(filename).readlines():
                
                iter = self.buffer.get_end_iter()
                self.buffer.insert(iter,line)
            
            file(filename).close()
            
            self.setTitle(filename)
            
        self.openFileDialog.hide()
            
    def on_openDialogCancelButton_clicked(self, widget):
        
        self.openFileDialog.hide()
        
    def on_openDialogOpenButton_clicked(self, widget):
        
        self.openFileDialog.hide()
        
    def on_subTextView_key_release_event(self, widget, event):
        
        #textBuffer = self.subTextView.get_buffer()
        
        if event.hardware_keycode == 13 or \
           (event.hardware_keycode == 36 and platform.system() == 'Darwin'):
            
            self.on_addEntryButton_clicked(widget)
            
    def on_saveToolButton_clicked(self, widget):
        
        self.openFileDialog.set_transient_for(self.main_window)
        self.openFileDialog.set_action(gtk.FILE_CHOOSER_ACTION_SAVE)
        self.openFileDialog.set_filename(self.currentFilename)
        
        image = gtk.Image()
        image.set_from_stock(gtk.STOCK_SAVE, gtk.ICON_SIZE_BUTTON)
        self.openDialogOpenButton.set_image(image)
        self.openDialogOpenButton.set_label("_Save")
        
        result = self.openFileDialog.run()
        
        if result == gtk.RESPONSE_OK:
            
            filename = self.openFileDialog.get_filename()
            
            # Output file
            outfile = open(filename, "w")
            outfile.write(self.buffer.get_text(self.buffer.get_start_iter(),
                                               self.buffer.get_end_iter(), include_hidden_chars=False))
            outfile.close()
            
            self.setTitle(filename)
        
    def on_copyToolButton_clicked(self, widget):
        
        """
        Copies the content of mainTextView to the clipboard.
        """
        
        startIter = self.buffer.get_start_iter()
        endIter   = self.buffer.get_end_iter()
        
        self.buffer.select_range(startIter, endIter)
        self.buffer.copy_clipboard(self.appClipboard)
        
        # Remove selection
        textBuffer.select_range(startIter, startIter)
        
    def setTitle(self, filename):
        
        self.currentFilename = os.path.basename(filename)
        
        self.main_window.set_title(self.baseTitle + " - " + self.currentFilename)
        
        self.buffer.set_modified(False)
        self.saveToolButton.set_sensitive(False)
        
    def insertText(self, text):
        
        """
        Insert text to mainTextView
        
        @param: text - the text to be inserted
        """
        
        endIter    = self.buffer.get_end_iter()
        
        self.buffer.insert(endIter, text)
        self.mainTextView.scroll_to_mark(self.buffer.get_insert(), 0.1)
        self.buffer.set_modified(True)
        
if __name__ == "__main__":
    
    j0urn4l = J0urn4l()
    
    gtk.main()
    